package com.cx.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cx.auth.model.vo.UserDetailsVO;
import com.cx.auth.utils.AuthTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

/**
 * @author zhangcx
 * @Description 将登录用户的JWT转化成用户信息的全局过滤器
 * @date 2022/6/8 16:49
 * @email zhangcx@bluemoon.com.cn
 */
@Component
@Slf4j
public class LimiterFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取ip
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String ipAddress = remoteAddress.getAddress().getHostAddress();
        // 打印获取到的IP地址
        log.info("Request IP Address: {}", ipAddress);
        // 将IP地址设置到请求的属性中，供后续的Filter或Handler使用
        exchange.getRequest().getHeaders().put("IP_ADDRESS", Collections.singletonList(ipAddress));
        //滑动窗口算法限制

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 没有token
     * @param exchange
     * @return
     */
    private Mono<Void> noTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.UNAUTHORIZED);
        json.put("data", "没有token");
        return jsonToMono(json, exchange);
    }

    /**
     * 将json字符串转换为Mono的格式,并添加到相应中去
     * @param json
     * @param exchange
     * @return
     */
    private Mono<Void> jsonToMono(JSONObject json, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = json.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        response.setStatusCode(HttpStatus.valueOf(HttpStatus.UNAUTHORIZED.name()));
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(dataBuffer));
    }


    private Mono<Void> invalidTokenMono(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.UNAUTHORIZED.value());
        json.put("data", "无效的token");
        return jsonToMono(json, exchange);
    }
    private Mono<Void> notLogin(ServerWebExchange exchange) {
        JSONObject json = new JSONObject();
        json.put("status", HttpStatus.NON_AUTHORITATIVE_INFORMATION);
        json.put("data", "请重新登录");
        return jsonToMono(json, exchange);
    }
}
